﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using HeritageAcademy.Library.Controls;
using HeritageAcademy.Models.DataModels;
using HeritageAcademy.Models.Loaders;

namespace HeritageAcademy.Models.ViewModels
{
    /// <summary>
    /// Users data handler.
    /// </summary>
    public class UsersDataHandler
    {
        #region Parameters
        
        private readonly UsersConfigLoader usersData;
        private UserTile userTile;
        
        #endregion

        #region Ctor
        
        public UsersDataHandler()
        {
            usersData = new UsersConfigLoader(new Users());
        }
        
        #endregion

        #region Properties

        /// <summary>
        /// Current user tile.
        /// </summary>
        public UserTile UserTile
        {
            get { return userTile; }
            set { userTile = value; }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Initialise users in login window list according to the xml database.
        /// </summary>
        /// <remarks>For my StackPanel as an user items collection</remarks>
        /// <param name="collection">Collection of UI elements UserTile add to</param>
        /// <param name="passwordHandler">Password key up event handler</param>
        /// <param name="folderPath">Path to folder with users image files</param>
        public void SetUsersList(UIElementCollection collection, KeyEventHandler passwordHandler, string folderPath)
        {
            collection.Clear();
            foreach (var t in usersData.Model.User)
            {
                userTile = new UserTile
                               {
                                   UserId = t.Id,
                                   Name = "user" + t.Login,
                                   UserName = t.Login,
                                   UserTitle = t.Role,
                                   Password = t.Password
                               };

                // Create source.
                var bi = new BitmapImage();
                bi.BeginInit();
                bi.UriSource = t.Icon != null ? new Uri(folderPath + "\\" + Shared.Properties.Resources.Application_Images + "\\" + t.Icon, UriKind.RelativeOrAbsolute) : new Uri(@"../../HeritageAcademy.Window/Window. Images/user_dima.png", UriKind.RelativeOrAbsolute);
                bi.EndInit();
                userTile.UserIcon = bi;

                userTile.Click += user_Click;
                userTile.PasswordInput.KeyUp += passwordHandler;
                collection.Add(userTile);
            }
        }

        /// <summary>
        /// Get current user data from database using its id 
        /// (private value of userTile.UserId).
        /// </summary>
        public User SetCurrentUser()
        {
            var currentUser = new User();
            
            // Search appropriate user in database
            foreach (var t in usersData.Model.User.Where(t => t.Id == userTile.UserId))
            {
                currentUser = t;
                t.Active = "true";
                usersData.Save();
            }
            return currentUser;
        }

        /// <summary>
        /// Get current user data from database using its id 
        /// (private value of userTile.UserId).
        /// </summary>
        public void UnSetCurrentUser()
        {
            foreach (var t in usersData.Model.User)
                t.Active = "false";
            usersData.Save();
        }

        /// <summary>
        /// Register new user.
        /// </summary>
        /// <param name="newUser">User object</param>
        /// <returns>True if registration succeded</returns>
        public bool RegisterNewUser(User newUser)
        {
            // TODO: implement FALSE (failure) situation
            usersData.Model.User.Add(newUser);
            usersData.Save();
            return true;
        }
        
        #endregion

        #region Event Handlers

        /// <summary>
        /// User tile click event handler.
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Routed event arguments</param>
        void user_Click(object sender, RoutedEventArgs e)
        {
            // Return previous user tile to it's initial state
            userTile.Margin = new Thickness(0, 5, 0, 20);
            userTile.PasswordBorder.Visibility = Visibility.Hidden;
            userTile.PasswordInput.Password = string.Empty;

            // Initialize current user tile
            userTile = sender as UserTile;
            var slideIn = ((UserTile)sender).FindResource("slideIn") as Storyboard;
            if (slideIn == null) return;
            slideIn.Completed += slideIn_Completed;
            slideIn.Begin((sender as UserTile));
        }

        /// <summary>
        /// Slide in completed event handler.
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Event arguments</param>
        void slideIn_Completed(object sender, EventArgs e)
        {
            var slideIn = userTile.FindResource("slideIn") as Storyboard;
            if (slideIn != null) slideIn.Completed -= slideIn_Completed;

            userTile.Margin = new Thickness(30, 5, 0, 50);
            userTile.PasswordBorder.Visibility = Visibility.Visible;
            userTile.PasswordInput.Focus();
        }

        #endregion
    }
}
